import os
import tempfile
import sqlite3

class TempFile(object):

    def __init__(self, contents=''):
        self.path = ''
        self.contents = contents

    def __enter__(self):
        self.path = tempfile.mktemp()
        f = open(self.path, 'w')
        f.write(self.contents)
        f.close()
        return self

    def __exit__(self, type, value, traceback):
        os.remove(self.path)


class TempDb(object):

    def __init__(self, script):
        self.path = ''
        self.script = script

    def __enter__(self):
        self.path = tempfile.mktemp()
        conn = sqlite3.connect(self.path)
        conn.executescript(self.script)
        conn.commit()
        conn.close()
        return self

    def __exit__(self, type, value, traceback):
        os.remove(self.path)


def flatten(seq):
    """flatten(sequence) -> list

    Returns a single, flat list which contains all elements retrieved
    from the sequence and all recursively contained sub-sequences
    (iterables).
     
    Examples:
    >>> [1, 2, [3,4], (5,6)]
    [1, 2, [3, 4], (5, 6)]
    >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
    [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
    result = []
    for el in seq:
        #if isinstance(el, (list, tuple)):
        if hasattr(el, "__iter__") and not isinstance(el, str):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result


def do_nothing(*args, **kwargs):
    '''do_nothing()->None'''


def identity(x):
    '''lambda x: x'''
    return x


def always_true(*args, **kwargs):
    '''lambda : True'''
    return True


def always_false(*args, **kwrags):
    return False


def trace(*args, **kwargs):
    print(args)
    print(kwargs)


def always(value):
    '''always(value)->lambda : value'''
    def inner(*args, **kwargs):
        return value
    return inner